const express = require("express");
const app = express();
const jwt = require("jsonwebtoken");
const expressJWT = require("express-jwt");
const cors = require("cors");

app.use(cors())
app.use(express.json())
app.use(express.urlencoded())

let serectKey = 'good';

app.use(
    expressJWT({secret:serectKey, algorithms:['HS256']})
    .unless({path:['/','/login',/\/ligin$/]})
)

app.post('/login',(req,res)=>{
    if(req.body.uname != 'admin' || req.body.pwd != '123456') {
        return res.send({msg:'用户名或者密码错误'})
    }

    let token = jwt.sign({uname:req.body.uname},serectKey,{expiresIn:'20s'})
    res.send({
        status: 200,
        msg:'登录成功',
        token:token
    })
})

app.get('/api/user',(req,res)=>{
    console.log(req.user)
    res.send({name:'user information',user:req.user})
})

app.get('/logout',(req,res)=>{

    res.send({
        msg:'退出成功',
        status:200
    })
})

app.use((err,req,res,next)=>{
    console.log(err.name)
    if(err.name=='UnauthorizedError') {
        return res.send({
            msg:'token 无效获取 请重新登录',
            status:401
        })
    }
    res.send({
        status:500,
        msg:'未知错误'
    })
    next()
})

app.listen(3000, () => {
    console.log("3000 running");
  });